package com.kujie.langchain4j.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 通用线程池工具类
 *
 * @author jyy
 * @date 2025-05-23
 */
public class ThreadPoolUtils {
    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolUtils.class);

    /**
     * 核心线程数
     */
    public static final int DEFAULT_CORE_POOL_SIZE = 10;

    /**
     * 最大线程数
     */
    public static final int DEFAULT_MAX_POOL_SIZE = 50;

    /**
     * 默认队列容量
     */
    public static final int DEFAULT_QUEUE_CAPACITY = 1000;

    /**
     * 线程空闲时间(秒)
     */
    public static final int DEFAULT_KEEP_ALIVE_SECONDS = 60;

    /**
     * 线程名前缀
     */
    public static final String DEFAULT_THREAD_NAME_PREFIX = "default-pool-";

    /**
     * 是否守护线程
     */
    public static final boolean DEFAULT_DAEMON = false;

    /**
     * 默认线程池实例
     */
    private static ThreadPoolTaskExecutor defaultExecutor;

    /**
     * 私有构造器
     */
    private ThreadPoolUtils() {
    }

    /**
     * 获取默认线程池(懒加载)
     */
    public static synchronized Executor getDefaultExecutor() {
        if (defaultExecutor == null) {
            defaultExecutor = createExecutor(
                    DEFAULT_CORE_POOL_SIZE,
                    DEFAULT_MAX_POOL_SIZE,
                    DEFAULT_QUEUE_CAPACITY,
                    DEFAULT_KEEP_ALIVE_SECONDS,
                    DEFAULT_THREAD_NAME_PREFIX,
                    DEFAULT_DAEMON
            );
        }
        return defaultExecutor;
    }

    /**
     * 自定义默认线程池配置
     *
     * @param corePoolSize     核心线程数
     * @param maxPoolSize      最大线程数
     * @param queueCapacity    队列容量
     * @param keepAliveSeconds 线程空闲时间(秒)
     * @param threadNamePrefix 线程名前缀
     * @param daemon           是否守护线程
     */
    public static synchronized void configDefaultExecutor(
            int corePoolSize,
            int maxPoolSize,
            int queueCapacity,
            int keepAliveSeconds,
            String threadNamePrefix,
            boolean daemon) {

        if (defaultExecutor != null) {
            logger.warn("默认线程池已创建，重新配置需要重启应用生效");
            return;
        }

        defaultExecutor = createExecutor(
                corePoolSize,
                maxPoolSize,
                queueCapacity,
                keepAliveSeconds,
                threadNamePrefix,
                daemon
        );
    }

    /**
     * 创建线程池(不注册到Spring容器)
     *
     * @param corePoolSize     核心线程数
     * @param maxPoolSize      最大线程数
     * @param queueCapacity    队列容量
     * @param keepAliveSeconds 线程空闲时间(秒)
     * @param threadNamePrefix 线程名前缀
     * @param daemon           是否守护线程
     * @return 线程池实例
     */
    public static ThreadPoolTaskExecutor createExecutor(
            int corePoolSize,
            int maxPoolSize,
            int queueCapacity,
            int keepAliveSeconds,
            String threadNamePrefix,
            boolean daemon) {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setDaemon(daemon);
        executor.initialize();

        logger.info("创建线程池: 核心[{}], 最大[{}], 队列[{}], 空闲[{}]秒, 前缀[{}], 守护[{}]",
                corePoolSize, maxPoolSize, queueCapacity,
                keepAliveSeconds, threadNamePrefix, daemon);

        return executor;
    }

    /**
     * 关闭线程池
     *
     * @param executor 线程池实例
     */
    public static synchronized void shutdown(ThreadPoolTaskExecutor executor) {
        if (executor != null) {
            executor.shutdown();
            logger.info("线程池[{}]已关闭", executor.getThreadNamePrefix());
        }
    }
}
